#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
#include "GameOverScene.h"

using namespace cocos2d;
using namespace CocosDenshion;

CCScene* HelloWorld::scene()
{
    // 'scene' is an autorelease object
    CCScene *scene = CCScene::create();
    
    // 'layer' is an autorelease object
    HelloWorld *layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

void HelloWorld::gameLogic()
{
    this->addTarget();
}

void HelloWorld::onExit()
{
    if (_targets) {
        _targets->release();
        _targets=NULL;
    }
    if (_projectiles) {
        _projectiles->release();
        _projectiles=NULL;
    }
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !CCLayerColor::initWithColor(ccc4(255,0,255,255)) )
    {
        return false;
    }
    
    /////////////////////////////
    // 1.5 game
    {
        _targets = new CCArray();
        _projectiles = new CCArray();
        
        CCSize winSize = CCDirector::sharedDirector()->getWinSize();
        CCSprite *player = CCSprite::create("Player.png");
        player->setPosition(ccp(winSize.width/2, 20));
        this->addChild(player);
        
        this->schedule(schedule_selector(HelloWorld::gameLogic), 1.0);
        this->schedule(schedule_selector(HelloWorld::update), 0.1);
        
        this->setTouchEnabled(true);
        
        //SimpleAudioEngine::sharedEngine()->playBackgroundMusic("background-music-aac.caf", true);
        
        return true;
    }
    /////////////////////////////
    // 2. add a menu item with "X" image, which is clicked to quit the program
    //    you may modify it.

    // add a "close" icon to exit the progress. it's an autorelease object
    CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
                                        "CloseNormal.png",
                                        "CloseSelected.png",
                                        this,
                                        menu_selector(HelloWorld::menuCloseCallback) );
    pCloseItem->setPosition( ccp(CCDirector::sharedDirector()->getWinSize().width - 20, 20) );

    // create menu, it's an autorelease object
    CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
    pMenu->setPosition( CCPointZero );
    this->addChild(pMenu, 1);

    /////////////////////////////
    // 3. add your codes below...

    // add a label shows "Hello World"
    // create and initialize a label
    CCLabelTTF* pLabel = CCLabelTTF::create("Hello World", "Thonburi", 34);

    // ask director the window size
    CCSize size = CCDirector::sharedDirector()->getWinSize();

    // position the label on the center of the screen
    pLabel->setPosition( ccp(size.width / 2, size.height - 20) );

    // add the label as a child to this layer
    this->addChild(pLabel, 1);

    // add "HelloWorld" splash screen"
    CCSprite* pSprite = CCSprite::create("HelloWorld.png");

    // position the sprite on the center of the screen
    pSprite->setPosition( ccp(size.width/2, size.height/2) );

    // add the sprite as a child to this layer
    this->addChild(pSprite, 0);
    
    return true;
}

void HelloWorld::addTarget()
{
    CCSprite * target = CCSprite::create("Target.png");
    // Determine where to spawn the target along the Y axis
    CCSize winSize = CCDirector::sharedDirector()->getWinSize();
    int minY = target->getContentSize().height/2;
    int maxY = winSize.height - target->getContentSize().height/2;
    int rangeY = maxY - minY;
    int actualY = (arc4random() % rangeY) + minY;
    
    // Create the target slightly off-screen along the right edge,
    // and along a random position along the Y axis as calculated above
    target->setPosition(ccp(0, actualY));
    target->setTag(1);
    _targets->addObject(target);
    this->addChild(target);

    // Determine speed of the target
    int minDuration =2.0;
    int maxDuration =4.0;
    int rangeDuration = maxDuration - minDuration;
    int actualDuration = (arc4random() % rangeDuration) + minDuration;
    
    // Create the actions
    CCMoveTo* actionMove = CCMoveTo::create(actualDuration, ccp(winSize.width + (target->getContentSize().width/2), actualY));
    
    CCAction * actionMoveDone = CCSequence::create(actionMove,
                                                CCCallFuncND::create(this,
                                                                     callfuncND_selector(HelloWorld::spriteMoveFinished),
                                                                     target),
                                                NULL);
    
    target->runAction(actionMoveDone);
}

void HelloWorld::spriteMoveFinished(CCSprite * sender)
{
    CCSprite *sprite = (CCSprite *)sender;
//    this->removeChild(sprite, true);
    if (sprite->getTag() == 1) {
        _targets->removeObject(sprite);
        //find
//        this->setTouchEnabled(false);
//        GameOverScene * gameOverScene = (GameOverScene *)GameOverScene::create();
//        gameOverScene->getlayer()->getlabel()->setString("You Lose!");
//        CCDirector::sharedDirector()->replaceScene(gameOverScene);
        
    } else if (sprite->getTag() == 2) {
        _projectiles->removeObject(sprite);
    }
}

void HelloWorld::update()
{
    CCArray * projectilesToDelete = new CCArray();
    for (int i = 0; i < _projectiles->count(); i++) {
        CCSprite * projectile = (CCSprite *)_projectiles->objectAtIndex(i);
        CCRect projectileRect = CCRectMake(projectile->getPosition().x,
                                           projectile->getPosition().y,
                                           projectile->getContentSize().width,
                                           projectile->getContentSize().height);
        
        CCArray * targetsToDelete = new CCArray();
        for (int j = 0; j < _targets->count(); j++) {
            CCSprite * target = (CCSprite *)_targets->objectAtIndex(j);
            CCRect targetRect = CCRectMake(target->getPosition().x,
                                           target->getPosition().y,
                                           target->getContentSize().width,
                                           target->getContentSize().height);
            
            if (targetRect.intersectsRect(projectileRect))
            {
                targetsToDelete->addObject(target);
            }
        }
        
        for (int k = 0; k < targetsToDelete->count(); k++) {
            CCSprite * target = (CCSprite *)targetsToDelete->objectAtIndex(k);
            _targets->removeObject(target);
            this->removeChild(target, true);
            
            _projectilesDestroyed++;
            if (_projectilesDestroyed > 20) {
                this->setTouchEnabled(false);
                GameOverScene *gameOverScene = (GameOverScene *)GameOverScene::create();
                gameOverScene->getlayer()->getlabel()->setString("You Win!");
                CCDirector::sharedDirector()->replaceScene(gameOverScene);
            }
        }
        if (targetsToDelete->count()>0) {
            projectilesToDelete->addObject(projectile);
        }
        targetsToDelete->release();
    }
    
    for (int z = 0; z < projectilesToDelete->count(); z++) {
        CCSprite * projectile = (CCSprite*)projectilesToDelete->objectAtIndex(z);
        _projectiles->removeObject(projectile);
        this->removeChild(projectile, true);
        
        _projectilesDestroyed++;
    }
    projectilesToDelete->release();
}

void HelloWorld::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent)
{
//    // Choose one of the touches to work with
    CCTouch* touch = (CCTouch*)pTouches->anyObject();
    CCPoint location = touch->getLocationInView();
    location = CCDirector::sharedDirector()->convertToGL(location);
    
    // Set up initial location of projectile
    CCSize winSize = CCDirector::sharedDirector()->getWinSize();
    CCSprite *projectile = CCSprite::create("Projectile.png");
    projectile->setPosition(ccp(winSize.width/2, 20));
    
    // Determine offset of location to projectile
    int offX = location.x;// - projectile->getPosition().x;
    int offY = location.y - projectile->getPosition().y;
    
    // Bail out if we are shooting down or backwards
    if (offX <=0) return;
    if (offY <=0) return;

    // Ok to add now - we've double checked position
    projectile->setTag(2);
    projectile->setColor(ccc3(255, 0, 0));
    _projectiles->addObject(projectile);
    this->addChild(projectile);
    
    // Determine where we wish to shoot the projectile to
    int realX = winSize.width;
    float ratio = (float) offY / abs(winSize.width/2 - (float) offX);
    int realY = (realX * ratio);
    
    int zidan = 0;//projectile->getContentSize().width;
    if (offX<winSize.width/2) {
        realX = -zidan;
    } else if (offX>winSize.width/2) {
        realX = winSize.width + zidan;
    }
    if (realY > winSize.height) {
        realY = winSize.height+zidan;
        if (offX<winSize.width/2) {
            realX = abs(realY/ratio-winSize.width/2);
        } else {
            realX = winSize.width/2 + realY/ratio;
        }
    }
    
    CCPoint realDest = ccp(realX, realY);

    // Determine the length of how far we're shooting
    int offRealX = realX - projectile->getPosition().x;
    int offRealY = realY - projectile->getPosition().y;
    float length = sqrtf((offRealX*offRealX)+(offRealY*offRealY));
    float velocity =480/1; // 480pixels/1sec
    float realMoveDuration = length/velocity;
    //do
    CCAction * actionMoveDone = CCSequence::create(CCMoveTo::create(realMoveDuration, realDest),
                                                   CCCallFuncND::create(this,
                                                                        callfuncND_selector(HelloWorld::spriteMoveFinished),
                                                                        NULL),
                                                   NULL);
    projectile->runAction(actionMoveDone);
    
    SimpleAudioEngine::sharedEngine()->playEffect("pew-pew-lei.caf");
}

void HelloWorld::menuCloseCallback(CCObject* pSender)
{
    CCDirector::sharedDirector()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
}
